#include <stdio.h>
#include "i2c_sgm3804.h"
#include "i2c_base.h"
#include "pin_name.h"
#include "drv_gpio.h"
#include "drv_delay.h"

#define SGM3804_VSP_EN_PIN		10
#define SGM3804_VSN_EN_PIN		5

#define SGM3804_AOGPIO_BASE						0xFFF02000
#define SGM3804_GPIO_SWPORTA_DR					0x0
#define SGM3804_GPIO_SWPORTA_DDR				0x4
#define MEM32(add) 						*((volatile unsigned long *)(add))

static uint32_t rd(uint32_t addr)
{
    uint32_t data;
    data = MEM32(addr);
    return data;
}

static void wr(uint32_t addr, uint32_t data)
{
    MEM32(addr) = data;
}

static void sgm3804_set_aogpio_high(uint8_t aogpio)
{
	uint32_t data;
	data = rd(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DDR);
	wr(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DDR, data | (1 << aogpio));
	data = rd(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DR);
	wr(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DR, data | (1 << aogpio));
}

static void sgm3804_set_aogpio_low(uint8_t aogpio)
{
	uint32_t data;
	data = rd(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DDR);
	wr(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DDR, data | (1 << aogpio));
	data = rd(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DR);
	wr(SGM3804_AOGPIO_BASE + SGM3804_GPIO_SWPORTA_DR, data & (~(1 << aogpio)));
}

int sgm3804_VSP_enable(void)
{
	int rtn;
    uint8_t reg;

    reg = SGM3804_5_5V;
    rtn = lcd_i2c_write(g_handle_bklgt_pwr, SGM3804_IIC_ADDR,
        SGM3804_REG0_POS, reg);     // 5.5v	
		
	sgm3804_set_aogpio_high(SGM3804_VSP_EN_PIN);	
	
	return rtn;
}

int sgm3804_VSP_disable(void)
{
	sgm3804_set_aogpio_low(SGM3804_VSP_EN_PIN);	
	return 0;
}

int sgm3804_VSN_enable(void)
{
	int rtn;
    uint8_t reg;

    reg = SGM3804_5_5V;
    rtn = lcd_i2c_write(g_handle_bklgt_pwr, SGM3804_IIC_ADDR,
        SGM3804_REG1_NEG, reg);     // -5.5v
		
	sgm3804_set_aogpio_high(SGM3804_VSN_EN_PIN);	
	
	return rtn;
}

int sgm3804_VSN_disable(void)
{
	sgm3804_set_aogpio_low(SGM3804_VSN_EN_PIN);	
	return 0;	
}

